<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@page import="db.*,java.sql.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Confirmation</title>
</head>
<body>
	<%
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String retypepwd = request.getParameter("retypepwd");
		String email = request.getParameter("email");
		PreparedStatement pstmt = DBUtil
				.prepareStatement("SELECT * FROM users WHERE user_name = ?");
		pstmt.setString(1, username);
		ResultSet rs = pstmt.executeQuery();
		if (rs.next()) {
			response.sendRedirect("register.jsp?error=1&username="
					+ username);
			return;
		}
		if (password == null || retypepwd == null
				|| !password.equals(retypepwd)) {
			response.sendRedirect("register.jsp?error=2");
			return;
		}
		pstmt = DBUtil
				.prepareStatement("SELECT * FROM users WHERE email = ?");
		pstmt.setString(1, email);
		rs = pstmt.executeQuery();
		if (rs.next()) {
			response.sendRedirect("register.jsp?error=3");
			return;
		}

		DBUtil.beginTransaction();
		pstmt = DBUtil
				.prepareStatement("INSERT INTO users (user_name, password, email) "
						+ "VALUES (?, md5(?), ?)");
		pstmt.setString(1, username);
		pstmt.setString(2, password);
		pstmt.setString(3, email);
		pstmt.execute();

		rs = pstmt.getGeneratedKeys();
		long userId = 0;
		if (rs.next()) {
			userId = Long.parseLong(rs.getString(1));
		}

		pstmt = DBUtil
				.prepareStatement("INSERT INTO user_roles (user_ref, user_name, role) "
						+ "VALUES (?, ?, 'applicant')");
		pstmt.setLong(1, userId);
		pstmt.setString(2, username);
		pstmt.execute();
		DBUtil.commitTransction();
		out.println("Your account has been sucessfully registered! <a href=\"applicant/name.jsp\">Login</a> now.");
	%>
</body>
</html>